/**
 * Worker服务
 * http ajax请求
 * 支持get、post
 * Time: 2020-12-16 dhc
 */
;function HttpCenter(){
    this.xhr = this.getXhr();
}
HttpCenter.prototype.getXhr = function(){
    return new XMLHttpRequest();
}
HttpCenter.prototype.ready = function(success){
    var xhr = this.xhr;
    xhr.addEventListener('load', function(e) {
        var status = xhr.status;
        if ((status >= 200 && status < 300) || status === 304) {
            var result;
            if (xhr.responseType === 'text') {
                result = xhr.responseText;
            } else if (xhr.responseType === 'document') {
                result = xhr.responseXML;
            } else {
                result = xhr.response;
            }
            typeof success === 'function' && success(result);
        }
    })
}
HttpCenter.prototype.get = function(obj){
    this.xhr.open('get', obj.url, true);
    this.xhr.send();
    this.ready(obj.success);
}
HttpCenter.prototype.post = function(obj){
    this.xhr.open('post', obj.url, true);
    this.xhr.send();
    this.ready(obj.success);
}


//发送请求状态200的结果到主线程
function PostMessage(hash, response){
    var object = {hash: hash, result: response};
    postMessage(JSON.stringify(object))
}
//接收主线程的请求信息
addEventListener("message", function(evt){

    var data = JSON.parse(evt.data);

    data.success = PostMessage.bind(this, data.hash);

    var http = new HttpCenter();

    switch (data.type) {
        case 'post' : http.post(data); break;
        case 'get': http.get(data); break;
        default: throw "请求方式"+ data.type +"，暂未定义相关请求."
    }

},false);